#include "Clip.h"
#include <tolua++.h>
#include <lua.hpp>
#include <lualib.h>
#include <lauxlib.h>
#include "Defs.h"
#include <assert.h>
#include <OgreLogManager.h>

#include "STGEngine.h"
//void CClip::update(float dt) {
//
//}
CClip::CClip()
: mTimeFunction()
, mCurrentTime(0)
, mTotalTime(10)
, mGlobalTime(0)
, mGlobalTotalTime(1000000.0f)
, mStopped(false)
, mRepeat(true)
, mGlobal(false)
{
    

}

void CClip::update( float timeElapsed )
{
    static lua_State *L = static_cast<CSTGEngine*>(CSTGEngine::getSingletonPtr())->lua();

    CClip *pClip = this;
    if (pClip->mStopped == false) {
        if (pClip->mGlobal && (pClip->mGlobalTime + timeElapsed > pClip->mGlobalTotalTime)) {
            timeElapsed = std::max<float>(0, pClip->mGlobalTotalTime - pClip->mGlobalTime);
            pClip->mStopped = true;
            //pClip->mGlobalTime = 0;
        }
        if ( ( (pClip->mCurrentTime + timeElapsed) > pClip->mTotalTime) && pClip->mRepeat == false) {
            timeElapsed = std::max<float>(0, (pClip->mTotalTime - pClip->mCurrentTime)/0.99f);
            pClip->mStopped = true;
        }
        lua_getglobal(L, pClip->mTimeFunction.c_str());
        if (lua_isnil(L, -1)) {
            LUA_ERROR(L);
        }
        tolua_pushnumber(L, timeElapsed);
        tolua_pushusertype(L, pClip, "CClip");
        if (lua_pcall(L, 2,0,0)) {
            //lua_error(L);
            LUA_ERROR(L);
        }
    }
}
//void CClip::load(const std::string &name, lua_State *L) {
//    if (luaL_dofile(L, name.c_str())) {
//        LUALOG(L);
//    }
//    GET_LUA_FLOAT(L, "total_time", mTotalTime);
//    GET_LUA_STRING(L, "script_name", mTimeFunction);
//    lua_pop(L, -1);
//}
